package com.xinting.piano.app;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.ActionBar;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hannesdorfmann.swipeback.Position;
import com.hannesdorfmann.swipeback.SwipeBack;
import com.xinting.piano.R;
import com.xinting.piano.data.PApp;
import com.xinting.piano.data.PMelody;
import com.xinting.piano.lib.network.PNetWork;
import com.xinting.piano.lib.storage.PStorage;
import com.xinting.piano.lib.util.PUtil;
import com.xinting.piano.service.PAlbum;
import com.xinting.piano.view.PControlView;

import java.io.IOException;

/**
 * Created by wuxinting on 15/11/1.
 * Record activity
 * record stop play(no album view)
 */
public class PRecordActivity extends PBaseActivity {

    /**
     * 计时器
     */
    private Chronometer chronometer;
    private PControlView recordView;
    private PControlView tryPlayView;
    private PControlView uploadView;
    private TextView titleLabel;
    private EditText titleEdit;
    private ProgressBar uploadProgressBar;

    private PAlbum album;
    private Handler handler;

    /**
     * 录制的时间
     */
    private long duration;

    public static final String LOG_TAG = PAlbum.LOG_TAG+"_record";
    private static final String TEMP_FILE_NAME = "audio.3gp";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SwipeBack.attach(this, Position.LEFT)
            .setContentView(R.layout.activity_record)
            .setSwipeBackView(R.layout.swipeback_default);

        ActionBar bar = getSupportActionBar();
        if (bar != null) {
            bar.setTitle(R.string.app_record);
        }

        try {
            album = new PAlbum(PStorage.getInstance().getFile(TEMP_FILE_NAME));
            album.setPlayComplete(new OnTryPlayCompleteListener());
        } catch (IOException e) {
            Log.e(LOG_TAG, e.getMessage());
        }

        recordView = $(R.id.album_record);
        tryPlayView = $(R.id.album_try_play);
        uploadView = $(R.id.album_upload);
        titleLabel = $(R.id.album_title_label);
        titleEdit = $(R.id.album_title);
        uploadProgressBar = $(R.id.album_record_progress);

        OnTitleEditListener titleEditListener = new OnTitleEditListener();
        titleEdit.setOnKeyListener(titleEditListener);
        titleEdit.setOnTouchListener(titleEditListener);
        titleLabel.setOnClickListener(new OnTitleLabelClickListener());
        recordView.setOnClickListener(new OnRecordListener());
        tryPlayView.setOnClickListener(new OnTryPlayListener());
        uploadView.setOnClickListener(new OnUploadListener());
        tryPlayView.setClickable(false);
        uploadView.setClickable(false);

        chronometer = $(R.id.timer);
        chronometer.setText("00'00");
        chronometer.setOnChronometerTickListener(new OnTickListener());

        handler = new UploadProgressHandler();
    }

    @Override
    public boolean onKeyUp(final int keyCode, final KeyEvent event) {
        // 当点击返回时，二次确认
        if (keyCode == KeyEvent.KEYCODE_BACK && uploadView.isClickable()) {
            PDialog dialog = new PDialog(this);
            dialog.setTitle(R.string.dialog_title_tip);
            dialog.setContent(R.string.record_quit_confirm);
            dialog.setCancelable(true);
            dialog.setOnPositiveListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    PRecordActivity.super.onKeyUp(keyCode, event);
                }
            }).show();
            return true;
        } else {
            return super.onKeyUp(keyCode, event);
        }
    }

    //record
    private boolean record(PControlView controlView) {
        //record and update view status
        if (album == null || !album.record()) {
            return false;
        }

        if (tryPlayView != null) {
            tryPlayView.setClickable(false);
        }

        if (uploadView != null) {
            uploadView.setClickable(false);
        }

        controlView.setStatus(PControlView.Status.STOP);

        //count
        chronometer.setBase(SystemClock.elapsedRealtime());
        chronometer.start();
        return true;
    }

    //stop record
    private void stopRecord(PControlView controlView) {
        if (album != null) {
            album.stopRecord();
        }

        if (tryPlayView != null) {
            tryPlayView.setClickable(true);
        }

        if (uploadView != null) {
            uploadView.setClickable(true);
        }

        controlView.setStatus(PControlView.Status.RECORD);

        chronometer.stop();
        duration = (SystemClock.elapsedRealtime() - chronometer.getBase());
    }

    //try to play
    private boolean tryPlay(PControlView controlView) {
        if (album != null) {
            if (album.getStatus() == PAlbum.Status.PAUSE) {
                album.resumePlay();
            } else {
                album.play();
            }
        } else {
            return false;
        }

        controlView.setStatus(PControlView.Status.PAUSE);

        chronometer.stop();
        return true;
    }

    //pause play
    private boolean pauseTryPlay(PControlView controlView) {
        if (album != null) {
            album.pausePlay();
        }

        controlView.setStatus(PControlView.Status.PLAY);

        chronometer.stop();
        return true;
    }

    //upload
    private boolean upload(PControlView controlView) {
        if (album == null) {
            return false;
        }

        //uploading
        if (album.getStatus() == PAlbum.Status.UPLOAD) {
            PUtil.toast(PApp.getAppContext(), $s(R.string.record_uploading));
            return true;
        }

        if (titleLabel.getVisibility() == View.GONE) {
            //no title yet
            titleEdit.setVisibility(View.VISIBLE);
            titleEdit.requestFocus();
            PUtil.showSoftInput(titleEdit, true);
            return false;
        }

        //show progress
        if (uploadProgressBar.getVisibility() != View.VISIBLE) {
            uploadProgressBar.setVisibility(View.VISIBLE);
            uploadProgressBar.setMax(0);
            uploadProgressBar.setProgress(0);
        }

        PMelody melody = new PMelody();
        melody.setTitle(titleLabel.getText().toString());
        melody.setDuration((int) (duration / 1000));
        album.upload(melody, new OnUploadProgress());
        return true;
    }

    /**
     * 当点击title的label时，修改名字
     */
    private class OnTitleLabelClickListener implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            titleEdit.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 监听回车事件, Close Touch Listener
     */
    private class OnTitleEditListener implements View.OnKeyListener, View.OnTouchListener {

        @Override
        public boolean onKey(View view, int i, KeyEvent keyEvent) {
            if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                if (view instanceof EditText) {
                    String title = ((EditText) view).getText().toString();
                    if (!title.isEmpty()) {
                        titleLabel.setText(title);
                        titleLabel.setVisibility(View.VISIBLE);
                    }
                    titleEdit.setVisibility(View.GONE);
                    PUtil.showSoftInput(titleEdit, false);
                }
            }
            return false;
        }

        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            final int RIGHT = 2;

            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                if (motionEvent.getRawX() >= (titleEdit.getRight() - titleEdit.getCompoundDrawables()[RIGHT].getBounds().width())) {
                    titleEdit.setVisibility(View.GONE);

                    InputMethodManager manager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                    manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
                    return true;
                }
            }
            return false;
        }
    }

    /**
     * 播放完成listener
     */
    private class OnTryPlayCompleteListener implements PAlbum.IPlayComplete {

        @Override
        public void onCompletion() {
            tryPlayView.setStatus(PControlView.Status.PLAY);
        }
    }

    //count timer
    private class OnTickListener implements Chronometer.OnChronometerTickListener {

        @Override
        public void onChronometerTick(Chronometer chronometer) {
            long delta = SystemClock.elapsedRealtime() - chronometer.getBase();
            chronometer.setText(DateFormat.format("mm''ss", delta));
        }
    }

    //click the record control
    private class OnRecordListener implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            if (view instanceof PControlView) {
                PControlView controlView = (PControlView) view;
                switch (controlView.getStatus()) {
                    case RECORD:
                        record(controlView);
                        break;
                    case STOP:
                        stopRecord(controlView);
                        break;
                    default:break;
                }
            }
        }
    }

    //click the play control
    private class OnTryPlayListener implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            if (view instanceof PControlView) {
                PControlView controlView = (PControlView) view;
                switch (controlView.getStatus()) {
                    case PLAY:
                        tryPlay(controlView);
                        break;
                    case PAUSE:
                        pauseTryPlay(controlView);
                        break;
                    default:break;
                }
            }
        }
    }

    //click upload
    private class OnUploadListener implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            if (view instanceof PControlView) {
                PControlView controlView = (PControlView) view;
                upload(controlView);
            }
        }
    }

    /**
     * 更新上传进度等UI
     */
    private class UploadProgressHandler extends Handler {

        public static final int WHAT_UPLOAD_PROGRESS = 0;

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case WHAT_UPLOAD_PROGRESS:
                    uploadProgressBar.setMax(msg.arg2);
                    uploadProgressBar.setProgress(msg.arg1);
                    if (msg.arg1 >= msg.arg2) {
                        uploadView.setClickable(false);
                        PUtil.toast(PApp.getAppContext(), $s(R.string.record_uploaded));
                        //上传完成后不用隐藏progressbar, 用户已经知道它是做什么的了
                    }
                break;
            }
        }
    }

    //上传进度
    private class OnUploadProgress implements PNetWork.IProgress {

        @Override
        public void onProgress(long cur, long max) {
            Message msg = Message.obtain();
            msg.what = UploadProgressHandler.WHAT_UPLOAD_PROGRESS;

            msg.arg1 = (int) (cur);
            msg.arg2 = (int) (max);
            if (max > Integer.MAX_VALUE) {
                msg.arg2 = 100;
                msg.arg1 = (int) (((float) cur / max) * 100);
            }
            handler.sendMessage(msg);
        }
    }
}
